package k8s

import (
	istioclient "istio.io/client-go/pkg/clientset/versioned"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
)

// 可以扩展为支持自定义资源的clientset
type K8sClientInterface interface {
	Kubernetes() kubernetes.Interface
	Master() string
	Config() *rest.Config
	Istio() istioclient.Interface
}

type KubernetesOptions struct {
	KubeConfig *rest.Config

	QPS float32 `json:"qps,omitemtpy" yaml:"qps"`

	Burst int `json:"burst,omitempty" yaml:"burst"`
}

func NewKubernetesOptionsWithConfig(kubeconfig *rest.Config) *KubernetesOptions {
	return &KubernetesOptions{
		KubeConfig: kubeconfig,
		QPS:        1e6,
		Burst:      1e6,
	}
}

type K8sClient struct {
	// kubernetes client interface
	k8s kubernetes.Interface

	master string

	config *rest.Config

	istio istioclient.Interface
}

func (k *K8sClient) Kubernetes() kubernetes.Interface {
	return k.k8s
}

func (k *K8sClient) Master() string {
	return k.master
}

func (k *K8sClient) Config() *rest.Config {
	return k.config
}

func (k *K8sClient) Istio() istioclient.Interface {
	return k.istio
}

func NewK8sClient(options *KubernetesOptions) (K8sClientInterface, error) {
	// 初始化config
	var config *rest.Config
	var err error

	config = options.KubeConfig
	config.QPS = options.QPS
	config.Burst = options.Burst

	// 初始化K8S client
	var k K8sClient
	k.k8s, err = kubernetes.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	//初始化istio client
	k.istio, err = istioclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	k.master = options.KubeConfig.Host
	k.config = config

	return &k, nil

}
